#include "log.h"
#include <regex.h>
#include <time.h>
// 全局变量定义（唯一实例）
// 文件的内容
FILE *log_fp = NULL;

LogLevel log_level_g = PROJECT_LOG_INFO; // 默认日志级别为INFO
// 多线程保护
pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
void logRecordLevel(LogLevel level, const char *fmt, ...)
{
    pthread_mutex_lock(&log_mutex);
    // 级别过滤检查
    if (level >= log_level_g)
    {
        pthread_mutex_unlock(&log_mutex);
        return;
    }

    // 声明变量
    time_t now;
    struct tm tm_info;
    char time_buf[20];

    // 格式化时间
    time(&now);
    localtime_r(&now, &tm_info);
    strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", &tm_info);

    // 级别标签映射
    const char *level_str = "UNKNOWN";
    switch (level)
    {
        case PROJECT_LOG_DEBUG:
            level_str = "DEBUG";
            break;
        case PROJECT_LOG_INFO:
            level_str = "INFO";
            break;
        case PROJECT_LOG_WARNING:
            level_str = "WARN";
            break;
        case PROJECT_LOG_ERROR:
            level_str = "ERROR";
            break;
    }

    // 日志内容格式化
    va_list args;
    va_start(args, fmt);
    char log_buf[1024];
    vsnprintf(log_buf, sizeof(log_buf), fmt, args);
    va_end(args);

    // 文件无误，打印到目标文件中，反之写入标准错误
    if (log_fp)
    {
        fprintf(log_fp, "[%s][%s][%s:%s:%d] %s\n", level_str, time_buf,
                __FILE__, __func__, __LINE__, log_buf);
        fflush(log_fp); // 确保及时写入，高频使用时，可以去掉
    }
    else
    {
        fprintf(stderr, "[%s][%s][%s:%s:%d] %s\n", level_str, time_buf,
                __FILE__, __func__, __LINE__, log_buf);
    }

    pthread_mutex_unlock(&log_mutex);
}

int logInit(LogLevel maxLevel, const char *filename)
{
    log_level_g = maxLevel;
    if (filename == NULL)
    {
        filename = "default.log";
    }
    log_fp = fopen(filename, "a");
    return log_fp ? 0 : -1;
}

void logClose()
{
    if (log_fp)
    {
        fclose(log_fp);
        log_fp = NULL;
    }
}
